﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;

using BotonJXC.BLL;
using BotonJXC.Entity;
using BotonJXC.DAO;
using BotonJXC.Util;
using NHibernate;

namespace BotonJXC.Forms.Controls
{
    public partial class UserInfoControl : BaseInfoControl
    {
        AccountBLL _accountBll = new AccountBLL();
        StoreBLL _storeBll = new StoreBLL();
        DepartmentBLL _departmentBll = new DepartmentBLL();
        RoleBLL _roleBll = new RoleBLL();

        IDictionary<int, IList<Department>> storeDeps = new Dictionary<int, IList<Department>>();

        string _username;
        string _realname;
        int _storeId;
        int _depId;
        int _roleId;
        private IList<Store> _stores;
        private IList<Role> _roles;
        public UserInfoControl()
        {
            InitializeComponent();
        }

        public override IList<object> SelectedItems
        {
            get
            {
                IList<object> selectedItems = new List<object>();
                foreach (DataGridViewRow r in kdgvUserInfo.SelectedRows)
                {
                    selectedItems.Add(r.DataBoundItem);
                }
                return selectedItems;
            }
        }

        public override void AddInfo()
        {
            base.AddInfo();
        }

        public override void SaveInfo()
        {
            ITransaction trans = HBHelper.BeginTransaction();
            try
            {
                foreach (DataGridViewRow r in kdgvUserInfo.Rows)
                {
                    Account acc = r.DataBoundItem as Account;
                    if (acc == null)
                        continue;
                    if (acc.UserId == 0)
                    {
                        _accountBll.Save(acc);
                    }
                    else if ("1".Equals(r.Tag) && acc.UserId != 0)
                    {
                        _accountBll.Update(acc);
                    }
                }
                trans.Commit();
            }
            catch (HibernateException ex)
            {
                trans.Rollback();
            }
            finally
            {
                HBHelper.Close();
            }
        }
        public override void DeleteInfo()
        {
            base.DeleteInfo();
        }
        

        private void UserInfoControl_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                LoadData();
                LoadRoleInfo();
                LoadStoreInfo();
            }
        }

        private void LoadData()
        {
            PageModel<Account> accounts = _accountBll.Find(_username, _realname, _depId, _roleId, pager1.PageStart, pager1.PageSize);
            pager1.TotalCount = accounts.TotalCount;
            kdgvUserInfo.DataSource = new BindingList<Account>(accounts.Results);

        }

        private void LoadRoleInfo()
        {
            _roles = _roleBll.FindAll();
            kcbRole.DataSource = _roles;
            DCRole.Items.Clear();
            foreach (Role r in _roles)
            {
                DCRole.Items.Add(r.RoleName);
            }
        }

        private void LoadStoreInfo()
        {
            _stores = _storeBll.FindAll();
            kcbStore.DataSource = _stores;
            DCStore.Items.Clear();
            foreach (Store s in _stores)
            {
                DCStore.Items.Add(s.StoreName);
            }
        }

        private void kdgvUserInfo_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            string colName = kdgvUserInfo.CurrentCell.OwningColumn.Name;
            if (e.Control is KryptonDataGridViewTextBoxEditingControl)
            {
                KryptonDataGridViewTextBoxEditingControl ctl = e.Control as KryptonDataGridViewTextBoxEditingControl;
                if (colName == "DCPassword")
                {
                    ctl.PasswordChar = '*';
                }
                else
                {
                    ctl.PasswordChar = new char();
                }
            }
            else if (e.Control is KryptonDataGridViewComboBoxEditingControl)
            {
                KryptonDataGridViewComboBoxEditingControl ctl = e.Control as KryptonDataGridViewComboBoxEditingControl;
                ctl.DropDownClosed += new EventHandler(ctl_DropDownClosed);
            }
        }

        void ctl_DropDownClosed(object sender, EventArgs e)
        {
            DataGridViewCell cell = kdgvUserInfo.CurrentCell;
            string colName = cell.OwningColumn.Name;
            KryptonDataGridViewComboBoxEditingControl ctl = sender as KryptonDataGridViewComboBoxEditingControl;
            if (colName == "DCStore" && ctl.SelectedIndex > -1)
            {
                DCDep.Items.Clear();
                cell.Tag = _stores[ctl.SelectedIndex];
                IList<Department> deps = loadDeps(_stores[ctl.SelectedIndex]);
                foreach (Department d in deps)
                {
                    DCDep.Items.Add(d.DepName);
                }
            }
            else if (colName == "DCRole" && ctl.SelectedIndex > -1)
            {
                IList<Account> accounts = kdgvUserInfo.DataSource as IList<Account>;
                accounts[cell.RowIndex].Role = _roles[ctl.SelectedIndex];
            }
            else if (colName == "DCDep" && ctl.SelectedIndex > -1)
            {
                Store store = kdgvUserInfo.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Tag as Store;
                if (store != null)
                {
                    IList<Account> accounts = kdgvUserInfo.DataSource as IList<Account>;
                    accounts[cell.RowIndex].Department = loadDeps(null)[ctl.SelectedIndex];
                }
            }
        }

        private void kdgvUserInfo_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
                kdgvUserInfo.Rows[e.RowIndex].Tag = "1";
        }

        private void kdgvUserInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            string colName = kdgvUserInfo.Columns[e.ColumnIndex].Name;
            IList<Account> accounts = kdgvUserInfo.DataSource as IList<Account>;
            if (colName == "DCPassword" && e.Value != null)
            {
                e.Value = new string('*', e.Value.ToString().Length);
            }
            else if (colName == "DCRole" && e.RowIndex < accounts.Count)
            {
                if(accounts[e.RowIndex].Role != null)
                    e.Value = accounts[e.RowIndex].Role.RoleName;
            }
            else if (colName == "DCStore" && e.RowIndex < accounts.Count)
            {
                if (accounts[e.RowIndex].Department != null && accounts[e.RowIndex].Department.Store != null)
                    e.Value = accounts[e.RowIndex].Department.Store.StoreName;
            }
            else if (colName == "DCDep" && e.RowIndex < accounts.Count)
            {
                if (accounts[e.RowIndex].Department != null)
                    e.Value = accounts[e.RowIndex].Department.DepName;
            }
            else if (colName == "DCEnabled" && e.RowIndex < accounts.Count)
            {
                e.Value = "Y".Equals(accounts[e.RowIndex].Enabled) ? "是":"否";
            }
        }

        private void kbQuery_Click(object sender, EventArgs e)
        {
            _username = ktbUsername.Text.Trim();
            _realname = ktbRealname.Text.Trim();
            if(kcbStore.SelectedValue != null)
                _storeId = (int)kcbStore.SelectedValue;
            if (kcbDepartment.SelectedValue != null)
                _depId = (int)kcbDepartment.SelectedValue;
            if (kcbRole.SelectedValue != null)
                _roleId = (int)kcbRole.SelectedValue;
            LoadData();
        }

        private void kcbStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            Store store = kcbStore.SelectedItem as Store;
            if (store != null)
            {
                IList<Department> departments = loadDeps(store);
                kcbDepartment.DataSource = departments;
            }
        }

        IList<Department> loadDeps(Store store)
        {
            IList<Department> departments = null;
            if (store == null)
            {
                return new List<Department>();
            }
            if (!storeDeps.TryGetValue(store.StoreId, out departments))
            {
                departments = _departmentBll.Find(null, store.StoreId, 0, 0, int.MaxValue).Results;
                storeDeps.Add(store.StoreId, departments);
            }
            return departments;
        }

        private void pager1_PageChanged(object sender, EventArgs e)
        {
            LoadData();
        }
    }
}
